<template>
  <div class="dashboard-container">
    <el-row :gutter="20">
      <!-- 欢迎卡片 -->
      <el-col :span="24">
        <el-card class="welcome-card">
          <div class="welcome-header">
            <div class="welcome-text">
              <h2>{{ welcomeText }}</h2>
              <p>欢迎使用学生管理系统</p>
            </div>
            <div class="date-time">
              <div class="date">{{ currentDate }}</div>
              <div class="time">{{ currentTime }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px">
      <!-- 统计卡片 -->
      <el-col :xs="24" :sm="12" :md="6" v-for="(item, index) in statCards" :key="index">
        <el-card class="stat-card" :body-style="{ padding: '20px' }">
          <div class="stat-card-content">
            <div class="stat-icon" :style="{ backgroundColor: item.color }">
              <i :class="item.icon"></i>
            </div>
            <div class="stat-info">
              <div class="stat-title">{{ item.title }}</div>
              <div class="stat-value">{{ item.value }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px">
      <!-- 通知列表 -->
      <el-col :span="16">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>最新通知</span>
              <el-button class="button" text @click="$router.push('/notification/list')">查看全部</el-button>
            </div>
          </template>
          <div v-loading="notificationLoading">
            <div v-if="notifications.length === 0" class="empty-text">暂无通知</div>
            <el-timeline v-else>
              <el-timeline-item
                v-for="item in notifications"
                :key="item.id"
                :timestamp="item.publishTime"
                :type="item.type === 1 ? 'danger' : 'primary'"
              >
                <el-card class="notification-card">
                  <div class="notification-title">
                    <span>{{ item.title }}</span>
                    <el-tag size="small" :type="item.type === 1 ? 'danger' : ''">
                      {{ item.type === 1 ? '重要通知' : '普通通知' }}
                    </el-tag>
                  </div>
                  <div class="notification-content">{{ item.contentPreview }}</div>
                  <div class="notification-footer">
                    <span>发布人: {{ item.publishUserName }}</span>
                    <el-button type="primary" link @click="viewNotification(item)">查看详情</el-button>
                  </div>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-card>
      </el-col>

      <!-- 快捷入口 -->
      <el-col :span="8">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>快捷入口</span>
            </div>
          </template>
          <div class="shortcut-list">
            <el-button
              v-for="(item, index) in shortcuts"
              :key="index"
              :type="item.type"
              :icon="item.icon"
              @click="$router.push(item.path)"
            >
              {{ item.title }}
            </el-button>
          </div>
        </el-card>

        <!-- 个人信息卡片 -->
        <el-card class="box-card" style="margin-top: 20px">
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
              <el-button class="button" text @click="$router.push('/profile/info')">编辑</el-button>
            </div>
          </template>
          <div class="user-info" v-loading="userLoading">
            <div class="user-avatar">
              <el-avatar :size="64" icon="el-icon-user"></el-avatar>
            </div>
            <div class="user-detail">
              <div class="user-name">{{ userInfo.realName || userInfo.username }}</div>
              <div class="user-role">
                <el-tag v-for="role in userInfo.roles" :key="role" size="small" style="margin-right: 5px">
                  {{ roleNames[role] || role }}
                </el-tag>
              </div>
              <div class="user-last-login" v-if="userInfo.lastLoginTime">
                上次登录: {{ userInfo.lastLoginTime }}
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 查看通知对话框 -->
    <el-dialog v-model="notificationDialogVisible" title="通知详情" width="700px">
      <div class="notification-view" v-if="currentNotification">
        <h2 class="notification-title">{{ currentNotification.title }}</h2>
        <div class="notification-meta">
          <span>发布人: {{ currentNotification.publishUserName }}</span>
          <span>发布时间: {{ currentNotification.publishTime }}</span>
          <el-tag :type="currentNotification.type === 1 ? 'danger' : ''">
            {{ currentNotification.type === 1 ? '重要通知' : '普通通知' }}
          </el-tag>
        </div>
        <div class="notification-content" v-html="currentNotification.content"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getDashboardData } from '@/api/dashboard'
import { getUserInfo } from '@/api/user'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const notificationLoading = ref(false)
const userLoading = ref(false)
const notifications = ref([])
const statCards = ref([])
const userInfo = ref({
  username: '',
  realName: '',
  roles: []
})

// 角色名称映射
const roleNames = {
  'ADMIN': '管理员',
  'DIRECTOR': '教导主任',
  'TEACHER': '教师',
  'STUDENT': '学生'
}

// 通知对话框
const notificationDialogVisible = ref(false)
const currentNotification = ref(null)

// 获取欢迎文本
const welcomeText = computed(() => {
  const hour = new Date().getHours()
  if (hour < 6) {
    return '凌晨好'
  } else if (hour < 9) {
    return '早上好'
  } else if (hour < 12) {
    return '上午好'
  } else if (hour < 14) {
    return '中午好'
  } else if (hour < 17) {
    return '下午好'
  } else if (hour < 19) {
    return '傍晚好'
  } else {
    return '晚上好'
  }
})

// 当前日期时间
const currentDate = computed(() => {
  const date = new Date()
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
})

const currentTime = computed(() => {
  const date = new Date()
  const week = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  return `${week[date.getDay()]}`
})

// 快捷入口
const shortcuts = computed(() => {
  const items = []
  
  // 根据角色显示不同的快捷入口
  if (userStore.hasPermission('notification:publish')) {
    items.push({
      title: '发布通知',
      icon: 'el-icon-edit',
      path: '/notification/publish',
      type: 'primary'
    })
  }
  
  if (userStore.hasPermission('course:add')) {
    items.push({
      title: '添加课程',
      icon: 'el-icon-plus',
      path: '/course/add',
      type: 'success'
    })
  }
  
  if (userStore.hasPermission('selection:apply')) {
    items.push({
      title: '选课申请',
      icon: 'el-icon-plus',
      path: '/selection/apply',
      type: 'success'
    })
  }
  
  if (userStore.hasPermission('selection:approve')) {
    items.push({
      title: '选课审批',
      icon: 'el-icon-s-check',
      path: '/selection/approve',
      type: 'warning'
    })
  }
  
  if (userStore.hasPermission('score:input')) {
    items.push({
      title: '成绩录入',
      icon: 'el-icon-edit',
      path: '/score/input',
      type: 'danger'
    })
  }
  
  if (userStore.hasPermission('score:my')) {
    items.push({
      title: '我的成绩',
      icon: 'el-icon-s-data',
      path: '/score/my',
      type: 'info'
    })
  }
  
  return items
})

// 获取仪表盘数据
const fetchDashboardData = async () => {
  notificationLoading.value = true
  try {
    const { data } = await getDashboardData()
    
    // 处理通知数据
    notifications.value = data.notifications.map(item => ({
      ...item,
      contentPreview: item.content.replace(/<[^>]+>/g, '').substring(0, 100) + (item.content.length > 100 ? '...' : '')
    }))
    
    // 处理统计卡片数据
    statCards.value = [
      {
        title: '课程总数',
        value: data.stats.courseCount || 0,
        icon: 'el-icon-reading',
        color: '#409EFF'
      },
      {
        title: '学生总数',
        value: data.stats.studentCount || 0,
        icon: 'el-icon-user',
        color: '#67C23A'
      },
      {
        title: '教师总数',
        value: data.stats.teacherCount || 0,
        icon: 'el-icon-s-custom',
        color: '#E6A23C'
      },
      {
        title: '通知总数',
        value: data.stats.notificationCount || 0,
        icon: 'el-icon-message',
        color: '#F56C6C'
      }
    ]
  } catch (error) {
    console.error('获取仪表盘数据失败:', error)
  } finally {
    notificationLoading.value = false
  }
}

// 获取用户信息
const fetchUserInfo = async () => {
  userLoading.value = true
  try {
    const { data } = await getUserInfo()
    userInfo.value = data
  } catch (error) {
    console.error('获取用户信息失败:', error)
  } finally {
    userLoading.value = false
  }
}

// 查看通知详情
const viewNotification = (notification) => {
  currentNotification.value = notification
  notificationDialogVisible.value = true
}

onMounted(() => {
  fetchDashboardData()
  fetchUserInfo()
})
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
  
  .welcome-card {
    background-color: #f0f2f5;
    
    .welcome-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .welcome-text {
        h2 {
          font-size: 24px;
          margin: 0;
          color: #303133;
        }
        
        p {
          margin: 10px 0 0;
          color: #606266;
        }
      }
      
      .date-time {
        text-align: right;
        
        .date {
          font-size: 16px;
          color: #606266;
        }
        
        .time {
          font-size: 14px;
          color: #909399;
          margin-top: 5px;
        }
      }
    }
  }
  
  .stat-card {
    margin-bottom: 20px;
    
    .stat-card-content {
      display: flex;
      align-items: center;
      
      .stat-icon {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;
        
        i {
          font-size: 24px;
          color: #fff;
        }
      }
      
      .stat-info {
        flex: 1;
        
        .stat-title {
          font-size: 14px;
          color: #909399;
          margin-bottom: 5px;
        }
        
        .stat-value {
          font-size: 24px;
          font-weight: bold;
          color: #303133;
        }
      }
    }
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .empty-text {
    text-align: center;
    color: #909399;
    padding: 30px 0;
  }
  
  .notification-card {
    margin-bottom: 10px;
    
    .notification-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: bold;
      margin-bottom: 10px;
    }
    
    .notification-content {
      color: #606266;
      margin-bottom: 10px;
    }
    
    .notification-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 12px;
      color: #909399;
    }
  }
  
  .shortcut-list {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .user-info {
    display: flex;
    align-items: center;
    
    .user-avatar {
      margin-right: 15px;
    }
    
    .user-detail {
      .user-name {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 5px;
      }
      
      .user-role {
        margin-bottom: 5px;
      }
      
      .user-last-login {
        font-size: 12px;
        color: #909399;
      }
    }
  }
  
  .notification-view {
    .notification-title {
      text-align: center;
      margin-bottom: 20px;
    }
    
    .notification-meta {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;
      color: #909399;
      font-size: 14px;
    }
    
    .notification-content {
      line-height: 1.8;
      padding: 20px;
      background-color: #f8f8f8;
      border-radius: 4px;
    }
  }
}
</style> 